package com.uroad.lib.util.encrypt;

import com.uroad.lib.data.Constant;

import org.bouncycastle.pqc.math.linearalgebra.ByteUtils;

import java.security.AlgorithmParameters;
import java.security.Key;
import java.security.Security;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;


public class AES128Helper {

    //算法名  
    private static final String KEY_ALGORITHM = "AES";
    //加解密算法/模式/填充方式  
    //可以任意选择，为了方便后面与iOS端的加密解密，采用与其相同的模式与填充方式  
    //ECB模式只用密钥即可对数据进行加密解密，CBC模式需要添加一个参数iv  
    private static final String CIPHER_ALGORITHM = "AES/CBC/PKCS5Padding";

    //生成密钥  
    private static byte[] generateKey() throws Exception {
        Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
        KeyGenerator keyGenerator = KeyGenerator.getInstance(KEY_ALGORITHM);
        keyGenerator.init(128);
        SecretKey key = new SecretKeySpec(Constant.AES_KEY.getBytes("utf-8"), "AES");//keyGenerator.generateKey();
        return key.getEncoded();
    }

    //生成iv
    private static AlgorithmParameters generateIV() throws Exception {
        byte[] iv = Constant.AES_IV.getBytes("utf-8");
        AlgorithmParameters params = AlgorithmParameters.getInstance(KEY_ALGORITHM);
        params.init(new IvParameterSpec(iv));
        return params;
    }

    //转化成JAVA的密钥格式
    private static Key convertToKey(byte[] keyBytes) throws Exception {
        SecretKey secretKey = new SecretKeySpec(keyBytes, KEY_ALGORITHM);
        return secretKey;
    }

    //加密
    public static String encrypt(String data) throws Exception {
        //转化为密钥
        Key key = convertToKey(generateKey());
        Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
        Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
        //设置为加密模式  
        cipher.init(Cipher.ENCRYPT_MODE, key, generateIV());
        return ByteUtils.toHexString(cipher.doFinal(data.getBytes()));
    }

    //解密  
    public static String decrypt(String data) throws Exception {
        byte[] encryptedData = ByteUtils.fromHexString(data);
        Key key = convertToKey(generateKey());
        Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
        //设置为解密模式  
        cipher.init(Cipher.DECRYPT_MODE, key, generateIV());
        return new String(cipher.doFinal(encryptedData), "UTF-8");
    }
}